import json
from django.http import JsonResponse
from django.views.generic import View
from ..models.Literature import Literature
import traceback
import requests
import hashlib
from utils.encryptionAndDecryptionUtil import get_useraccount_from_request
from control.models.User import User

baidu_api_key = 'dui2u6KWCkFsOUuMPMIs'
baidu_app_id = '20240111001938261'
baidu_api_url = 'http://api.fanyi.baidu.com/api/trans/vip/translate'


def translate_text_baidu(text, from_lang='auto', to_lang='zh'):
    # 构建请求参数
    params = {
        'q': text,
        'from': from_lang,
        'to': to_lang,
        'appid': baidu_app_id,
        'salt': '123456',  # 随机数
        'sign': '',        # 签名，稍后计算
    }

    # 计算签名
    sign_str = baidu_app_id + text + params['salt'] + baidu_api_key
    params['sign'] = hashlib.md5(sign_str.encode()).hexdigest()

    # 发送请求
    response = requests.get(baidu_api_url, params=params)
    result = response.json()

    # 输出翻译结果
    if 'trans_result' in result:
        translated_text = result['trans_result'][0]['dst']
        return translated_text
    else:
        print('翻译失败')
        return '翻译失败'

class LiterChineseFieldsView(View):
    def get(self, request, id):
        res = {"code": 400, "message": "", "data": None}
        try:
            liter = Literature.objects.get(uuid=id)
            data = request.GET
            chinese_fields = data.getlist('chinese_fields[]', [])
            
            res_data = []
            if 'title' in chinese_fields:
                title = liter.title
                translated_title = translate_text_baidu(title)
                res_data.append({"field_data_index": "title", "field_name": "引文名称", "field_init_text": title, "field_chinese_text": translated_title, "is_selected": False})
            
            if "authors" in chinese_fields:
                authors = liter.authors.all()
                for author in authors:
                    author_name = author.name
                    translated_author_name = translate_text_baidu(author_name)
                    res_data.append({"field_data_index": "authors", "field_name": "作者列表", "field_init_text": author_name, "field_chinese_text": translated_author_name, "is_selected": False})

            if "keywords" in chinese_fields:
                keywords = liter.keywords.all()
                for keyword in keywords:
                    keyword_name = keyword.k
                    translated_keyword_name = translate_text_baidu(keyword_name)
                    res_data.append({"field_data_index": "keywords", "field_name": "关键词列表", "field_init_text": keyword_name, "field_chinese_text": translated_keyword_name, "is_selected": False})
                
            if "pub_name" in chinese_fields:
                pub = liter.pub_id
                if pub:
                    pub_name = pub.name
                    translated_pub_name = translate_text_baidu(pub_name)
                    res_data.append({"field_data_index": "pub_name", "field_name": "来源出版物名称", "field_init_text": pub_name, "field_chinese_text": translated_pub_name, "is_selected": False})
                   
            res["code"] = 200
            res["message"] = "检索成功"
            res["data"] = res_data
        except Exception as e:
            traceback.print_exc()
            res["code"] = 500
            res["message"] = "服务器错误：" + str(e)
        return JsonResponse(res)
    
    
class LiterChineseInfoView(View):
    def put(self, request, id):
        res = {"code": 400, "message": "", "data": None}
        try:
            liter = Literature.objects.get(uuid=id)
            
            user_name = get_useraccount_from_request(request=request)
            u = User.objects.filter(user_account=user_name)[0]
            data = json.loads(request.body)
            
            for item in data:
                if item['field_data_index'] == "title":
                    liter.zh_title = item['field_chinese_text']
                elif item['field_data_index'] == "authors":
                    author_name = item['field_init_text']
                    author = liter.authors.filter(name=author_name).first()
                    if author:
                        author.zh_name = item['field_chinese_text']
                        author.save()
                elif item['field_data_index'] == "keywords":
                    keyword_name = item['field_init_text']
                    keyword = liter.keywords.filter(k=keyword_name).first()
                    if keyword:
                        keyword.v = item['field_chinese_text']
                        keyword.save()
                elif item['field_data_index'] == "pub_name":
                    pub = liter.pub_id
                    if pub:
                        pub.zh_name = item['field_chinese_text']
                        pub.save()
                else:
                    res["code"] = 400
                    res["message"] = "未知字段"
                    return JsonResponse(res)
            
            liter.last_editor = u
            liter.save()
            res["code"] = 200
            res["message"] = "汉化信息修改成功"
            res["data"] = None
        except Exception as e:
            traceback.print_exc()
            res["code"] = 500
            res["message"] = "服务器错误：" + str(e)
        return JsonResponse(res)